<?php
class Series_season_model extends CI_Model{
	
	function __construct(){
		parent::__construct();
		$this->load->database();
	}
	
	
	/**
	 *  METODOS DE THETVDB
	 * 
	 * Busca series espesificando el ID y obtiene todas sus temporada con sus episodios
	 */
	public function getAllInfoSeason($params){
		$tv = new TV_Shows();
		
		$data = $tv->findById($params['id_tvdb'], $search=false, $all=true);
		
		$res = array('episode_list' => array());
		$epi_data = array();
		$bool = FALSE;
		$total_u = 0;
		$total_i = 0;

		foreach ($data['Episode'] as $episode) {
			
			if($episode['Combined_season']==$params['season_number']){
				$bool = TRUE;
				if($this->exist('series_capitulos',array( 'id_temporada' => $params['season'], 'no_capitulo' => $episode['EpisodeNumber']))){
					$epi_data = array(
							'titulo'		=> is_array($episode['EpisodeName']) ? 'Episode '.$episode['EpisodeNumber'] : $episode['EpisodeName'],
							'fecha_estreno'	=> is_array($episode['FirstAired']) ? NULL : $episode['FirstAired']
						);

					$this->db->where(array('id_temporada' => $params['season'] , 'no_capitulo' => $episode['EpisodeNumber']));
					$this->db->update('series_capitulos',$epi_data);
					$total_u++;
				}
				else{
					$this->load->model('user_model');
					$res = $this->user_model->getIdUserToken($params);
					$data_usr = $res->row_array();
					
					$epi_data = array(
						'id_temporada'		=> $params['season'],
						'id_usuario' 		=> $data_usr['id_usuario'],
						'no_capitulo' 		=> $episode['EpisodeNumber'],
						'titulo' 			=> is_array($episode['EpisodeName']) ? 'Episode '.$episode['EpisodeNumber'] : $episode['EpisodeName'],
						// 'titulo_limpio' => Sys::toAscii(is_array($episode['EpisodeName']) ? 'Episode '.$episode['EpisodeNumber'] : $episode['EpisodeName']),
						'status'			=> 0
					);
					
					if(!is_array($episode['FirstAired'])){
						$epi_data['fecha_estreno'] = $episode['FirstAired'];
					}
					
					$this->db->insert('series_capitulos', $epi_data);
					$total_i++;
				}
				unset($epi_data);
			}
		}
			if($bool)
				return array('action' => $bool, 'msg' => $total_u.' Actualizado(s) y '.$total_i.' Nuevo(s)');
			else
				return $bool;
	}
	
	private function exist($table, $sql, $return_res=false){
		$res = $this->db->get_where($table, $sql);
		if($res->num_rows() > 0){
			if($return_res)
				return $res->row();
			return TRUE;
		}
		return FALSE;
	}
}